package com.gdth.log;

import java.util.ArrayList;
import java.util.List;

import android.os.PowerManager.WakeLock;
import android.util.Log;

/**
 * 
 * @author mac1
 * 日志收集 1.清除日志缓存 2.杀死应用程序已开启的Logcat进程防止多个进程写入一个日志文件 3.开启日志收集进程 4.处理日志文件 移动
 */
public class LogCollectorThread extends Thread {
	private static final String TAG = "LogCollectorThread";
	
	private WakeLock wakeLock;
	private LogServer mLogServer;
	
    public LogCollectorThread(WakeLock wakeLock, LogServer mLogServer) {
        super("LogCollectorThread");
        Log.d(TAG, "LogCollectorThread is create");
        
        this.wakeLock = wakeLock;
        this.mLogServer = mLogServer;
    }

    @Override
    public void run() {
        try {
            wakeLock.acquire(); // 唤醒手机

            clearLogCache();

            List<String> orgProcessList = getAllProcess();
            List<ProcessInfo> processInfoList = LogUtil.getProcessInfoList(orgProcessList);
            mLogServer.killLogcatProc(processInfoList);

            mLogServer.createLogCollector();

            Thread.sleep(1000);// 休眠，创建文件，然后处理文件，不然该文件还没创建，会影响文件删除

            mLogServer.handleLog();

            wakeLock.release(); // 释放
        } catch (Exception e) {
            e.printStackTrace();
            mLogServer.recordLogServiceLog(Log.getStackTraceString(e));
        }
    }
    
    /**
     * 每次记录日志之前先清除日志的缓存, 不然会在两个日志文件中记录重复的日志
     */
    private void clearLogCache() {
        Process proc = null;
        List<String> commandList = new ArrayList<String>();
        commandList.add("logcat");
        commandList.add("-c");
        try {
            proc = Runtime.getRuntime().exec(commandList.toArray(new String[commandList.size()]));
            StreamConsumer errorGobbler = new StreamConsumer(proc.getErrorStream());

            StreamConsumer outputGobbler = new StreamConsumer(proc.getInputStream());

            errorGobbler.start();
            outputGobbler.start();
            if (proc.waitFor() != 0) {
                Log.e(TAG, " clearLogCache proc.waitFor() != 0");
                mLogServer.recordLogServiceLog("clearLogCache clearLogCache proc.waitFor() != 0");
            }
        } catch (Exception e) {
            Log.e(TAG, "clearLogCache failed", e);
            mLogServer.recordLogServiceLog("clearLogCache failed");
        } finally {
            try {
                proc.destroy();
            } catch (Exception e) {
                Log.e(TAG, "clearLogCache failed", e);
                mLogServer.recordLogServiceLog("clearLogCache failed");
            }
        }
    }

    /**
     * 运行PS命令得到进程信息
     * 
     * @return USER PID PPID VSIZE RSS WCHAN PC NAME root 1 0 416 300 c00d4b28
     *         0000cd5c S /init
     */
    private List<String> getAllProcess() {
        List<String> orgProcList = new ArrayList<String>();
        Process proc = null;
        try {
            proc = Runtime.getRuntime().exec("ps");
            StreamConsumer errorConsumer = new StreamConsumer(
                    proc.getErrorStream());

            StreamConsumer outputConsumer = new StreamConsumer(
                    proc.getInputStream(), orgProcList);

            errorConsumer.start();
            outputConsumer.start();
            if (proc.waitFor() != 0) {
                Log.e(TAG, "getAllProcess proc.waitFor() != 0");
                mLogServer.recordLogServiceLog("getAllProcess proc.waitFor() != 0");
            }
        } catch (Exception e) {
            Log.e(TAG, "getAllProcess failed", e);
            mLogServer.recordLogServiceLog("getAllProcess failed");
        } finally {
            try {
                proc.destroy();
            } catch (Exception e) {
                Log.e(TAG, "getAllProcess failed", e);
                mLogServer.recordLogServiceLog("getAllProcess failed");
            }
        }
        return orgProcList;
    }
}
